package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.tjvib.R;
import com.tjvib.TJVIBAPP;
import com.tjvib.adapter.ReportAdapter;
import com.tjvib.base.BaseActivity;
import com.tjvib.bean.DataSetInfo;
import com.tjvib.bean.ReportBean;
import com.tjvib.common.Callback;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.util.FileUtil;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.PayUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.view.dialog.HintDialog;
import com.tjvib.widget.AndroidScheduler;
import com.tjvib.widget.SlideRecyclerView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.EasyPermissions;

public class ReportActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{

    private TextView rep_tv_hint;
    public SlideRecyclerView rep_srv;
    private ReportAdapter reportAdapter;
    private List<ReportBean> fileList = new ArrayList<>();

    public BottomFileDialog bottomFileDialog;

    String[] perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    int RC_READ_AND_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_report;
    }

    @Override
    protected boolean initView() {
        rep_srv = findViewById(R.id.rep_srv);
        rep_tv_hint = findViewById(R.id.rep_tv_hint);
        return true;
    }

    @Override
    protected boolean initData() {
        if (!EasyPermissions.hasPermissions(ReportActivity.this, perms)) {
            EasyPermissions.requestPermissions(ReportActivity.this, "请授予APP读写存储卡权限", RC_READ_AND_WRITE_EXTERNAL_STORAGE, perms);
        }

        bottomFileDialog = new BottomFileDialog(this, R.style.DialogTheme);

        File downloadDir = TJVIBAPP.getApplication().getExternalFilesDir(null);
        File[] files = downloadDir.listFiles((dir, name) -> name.endsWith(".docx"));
        for (File file : files) {
            fileList.add(new ReportBean(file.getName(), getFileLastModifiedTime(file)));
        }

        reportAdapter = new ReportAdapter(this, R.layout.item_file, fileList, ReportActivity.this);

        rep_srv.setLayoutManager(new LinearLayoutManager(this));
        LinearSnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(rep_srv);
        rep_srv.setAdapter(reportAdapter);

        if (fileList != null && fileList.size() != 0)
            rep_tv_hint.setVisibility(View.INVISIBLE);
        else
            rep_tv_hint.setVisibility(View.VISIBLE);
        return true;
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    public void showDeleteReportDialog(ReportBean reportBean) {
        runOnUiThread(() -> {
            HintDialog hintDialog = new HintDialog(this);
            hintDialog.showDialog(this, "警告",
                    "删除报告后将不可恢复，请谨慎操作",
                    view -> {
                        hintDialog.dismiss();
                        FileUtil.deleteReportFile(reportBean.getName());
                        rep_srv.closeMenu();
                        fileList.remove(reportBean);
                        reportAdapter.notifyDataSetChanged();
                    },
                    view -> hintDialog.dismiss());
        });
    }


    public String getFileLastModifiedTime(File file) {
        String formatType = "yyyy年MM月dd日 HH:mm:ss";
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Calendar cal = Calendar.getInstance();
        long time = file.lastModified();
        cal.setTimeInMillis(time);
        return formatter.format(cal.getTime());
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            ToastUtil.show("请您前往本手机设置手动开启权限");
        }
    }

    public class BottomFileDialog extends BottomSheetDialog {
        public BottomFileDialog(@NonNull Context context, int themeResId) {
            super(context, themeResId);
        }

        public void showBottomDialog(Context context, ReportBean reportBean) {
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_bottom_file, null);
            this.setContentView(view);
            this.setCanceledOnTouchOutside(true);
            this.show();

            this.findViewById(R.id.dialog_bot_file_tv_open).setOnClickListener(view0 -> {
                if (!EasyPermissions.hasPermissions(ReportActivity.this, perms)) {
                    EasyPermissions.requestPermissions(ReportActivity.this, "请授予APP读写存储卡权限", RC_READ_AND_WRITE_EXTERNAL_STORAGE, perms);
                } else {
                   FileUtil.openReportFile(getContext(), reportBean.getName(), new Callback() {
                                @Override
                                public void onSuccess(String message, String data) {
                                }

                                @Override
                                public void onFail(String message, String data) {
                                    showErrorDialog("打开失败：" + message);
                                }

                                @Override
                                public void onError(String message, String data) {
                                    showErrorDialog("打开失败：" + message);
                                }
                            });
                        }

                    dismiss();
            });

            this.findViewById(R.id.dialog_bot_file_tv_share).setOnClickListener(view12 -> {
                dismiss();
                if (!EasyPermissions.hasPermissions(ReportActivity.this, perms)) {
                    EasyPermissions.requestPermissions(ReportActivity.this, "请授予APP读写存储卡权限", RC_READ_AND_WRITE_EXTERNAL_STORAGE, perms);
                } else {
                    FileUtil.shareReportFile(ReportActivity.this, reportBean.getName());
                }
            });

            this.findViewById(R.id.dialog_bot_file_tv_cancel).setOnClickListener(view13 -> dismiss());
        }
    }
}